package com.ning.parking.config;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.ning.parking.domain.ParkingUserInfo;
import com.ning.parking.service.ParkingUserInfoService;
import com.ning.parking.utils.ExpiryMap;
import com.scsonic.framework.common.constant.SecurityConstants;
import com.scsonic.framework.util.ServletUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.List;


/**
 * 全局本地缓存
 *
 * @author 91447
 */
@Slf4j
public class GlobalVariableUtils {

    /**
     * 自带过期时间
     */
    private static ExpiryMap<String, ParkingUserInfo> LOGIN_USER = new ExpiryMap();



    public static void setUser(String key,ParkingUserInfo userLastLogin) {
        LOGIN_USER.put(key, userLastLogin,1000*60*60*24);
    }

    public static ParkingUserInfo getUser(String key) {
        ParkingUserInfo parkingUserInfo = LOGIN_USER.get(key);
        return parkingUserInfo;
    }

    public static ParkingUserInfo getUser() {
        String token = getToken(ServletUtils.getRequest());

        if (token==null){
            return new ParkingUserInfo();
        }

        ParkingUserInfo parkingUserInfo = LOGIN_USER.get(token);

        if (parkingUserInfo==null){
            ParkingUserInfoService bean = SpringUtil.getBean(ParkingUserInfoService.class);
            List<ParkingUserInfo> list = bean.lambdaQuery().eq(ParkingUserInfo::getToken, token).list();
            if (list!=null&&list.size()>0){
                parkingUserInfo = list.get(0);
            }
            if (parkingUserInfo != null){
                return parkingUserInfo;
            }
            return new ParkingUserInfo();
        }

        return parkingUserInfo;
    }

    public static String getToken(HttpServletRequest request) {
        // 从header获取token标识
        String token = request.getHeader(SecurityConstants.HEADER);

        if (ObjectUtil.isEmpty(token)){
            token = request.getHeader(SecurityConstants.AUTHORIZATION_HEADER);
        }

        return replaceTokenPrefix(token);
    }

    /**
     * 裁剪token前缀
     */
    public static String replaceTokenPrefix(String token) {
        // 如果前端设置了令牌前缀，则裁剪掉前缀
        if (StringUtils.isNotEmpty(token) && token.startsWith(SecurityConstants.TOKEN_PREFIX)) {
            token = token.replaceFirst(SecurityConstants.TOKEN_PREFIX, "");
        }
        return token;
    }

}
